package com.lst.servlet;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.SportRecordsReqPara;
import com.lst.entity.response.SportRecordsResPara2;
import com.lst.model.PlanCourse;
import com.lst.model.SportRecords;
import com.lst.service.PlanCourseService;
import com.lst.service.PlanService;
import com.lst.service.SportRecordsService;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;


/**
 * @ClassName: SportRecordsAddServlet
 * @Description: 运动记录添加接口
 * 
 */
public class SportRecordAddServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private SportRecordsService sportRecordsService = ctx.getBean(SportRecordsService.class);
	
	private PlanCourseService planCourseService = ctx.getBean(PlanCourseService.class);
	
	private PlanService planService = ctx.getBean(PlanService.class);
	
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);
		SportRecordsResPara2 resPara = new SportRecordsResPara2();

		try {
			SportRecordsReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
			Integer userid = Integer.valueOf(reqPara.getUserid());
			Integer enterType = Integer.valueOf(reqPara.getEnterType());
			Integer courseId = Integer.valueOf(reqPara.getCourseId());
			Integer trainTime = Integer.valueOf(reqPara.getTrainTime());
			Integer calories = Integer.valueOf(reqPara.getCalories());
			Integer feelStatus=StringUtils.isEmpty(reqPara.getFeelStatus()) ? 0 : Integer.valueOf(reqPara.getFeelStatus());
			String actionNum = StringUtils.isEmpty(reqPara.getActionNum()) ? null : reqPara.getActionNum();	
			String title = reqPara.getTitle();
			String trainDate=StringUtils.isEmpty(reqPara.getTrainDate()) ? null : reqPara.getTrainDate();
			Integer planId=0;
			
			if(enterType==1){//从计划里面完成课程
				 //Date trainDate=DateUtil.getFormatDate(startDate, DateUtil.ALL_DATE_HORIZONTAL);//日期转换个格式
				 Map<String,Object> map=new HashMap<String,Object>();
	    		 map.put("courseId",courseId);
	    		 map.put("planStatus",1);
	    		 map.put("trainDate",trainDate);
	    		 map.put("createUser",userid);
	    		 PlanCourse planCourse=planCourseService.selectByMap(map);
	    		 if(planCourse!=null){
	    			 planCourseService.update(planCourse);
	    			 
		    		 planId=planCourse.getPlanId();
		    		 
		    		 Map<String,Object> map2=new HashMap<String,Object>();
		    		 map2.put("planId",planId);
		    		 map2.put("createUser",userid);
		    		 map2.put("planStatus",1);
		    		 int num=planCourseService.countByStatus(map2);//查询用户训练计划课程是否结束
		    		 if(num==0){//计划完成
		    			 Map<String,Object> map3=new HashMap<String,Object>();
			    		 map3.put("createUser",userid);
			    		 map3.put("status",1);
			    		 planService.updateByMap(map3);
		    		 }
		    		 
	    		 }
	    		 
			}
			Map<String,Object> reqmap=new HashMap<String,Object>();
			reqmap.put("createUser",userid);
		    reqmap.put("courseId",courseId);
			int trainNum=sportRecordsService.countByMap(reqmap);
			String content="完成  "+title+"第"+(trainNum+1)+" 次训练";
			
			SportRecords sportRecord = new SportRecords();
			
		    SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
			Calendar date = Calendar.getInstance();
			date.setTime(startDate);
			date.set(Calendar.DATE, date.get(Calendar.DATE) - 1);
			Date endDate = dft.parse(dft.format(date.getTime()));
			Map<String,Object> reqmap2=new HashMap<String,Object>();
			reqmap2.put("createUser",userid);
		    reqmap2.put("createDate2",endDate);
		    List<SportRecords>  sportRecordsList=sportRecordsService.queryByList(reqmap2);
		    if(sportRecordsList!=null&&sportRecordsList.size()>0){
		    	int num=sportRecordsList.get(0).getTotalNum();
		    	sportRecord.setTotalNum(num+1);
		    }else{
		    	sportRecord.setTotalNum(1);
		    }
		    
			sportRecord.setIsDelete(false);
			sportRecord.setCourseId(courseId);
			sportRecord.setTrainTime(trainTime);
			sportRecord.setCalories(calories);
			sportRecord.setFeelStatus(feelStatus);
			sportRecord.setActionNum(actionNum);
			sportRecord.setCreateUser(userid);
			sportRecord.setCreateDate(startDate);
			sportRecord.setEnterType(enterType);
			sportRecord.setTitle(title);
			sportRecord.setContent(content);
			sportRecord.setCreateDate2(startDate);
			sportRecord.setPlanId(planId);
			sportRecordsService.insert(sportRecord);
			
			resPara.setRecordId(sportRecord.getId());
			resPara.setCode(CommCode.M_Y000000);
			resPara.setMessage(CommCode.M_Y000001);
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);
			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info("SportRecordAddServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public SportRecordsReqPara getReqPara(HttpServletRequest request) {

		SportRecordsReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new SportRecordsReqPara());

			reqPara = (SportRecordsReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String enterType=request.getParameter("enterType");
			String courseId=request.getParameter("courseId");
			String trainTime=request.getParameter("trainTime");
			String calories=request.getParameter("calories");
			String feelStatus=request.getParameter("feelStatus");
			String actionNum=request.getParameter("actionNum");
			String title=request.getParameter("title");
			String trainDate=request.getParameter("trainDate");
	
			logger.info("reqPara userid:" + userid);
			logger.info("reqPara enterType:" + enterType);
			logger.info("reqPara courseId:" + courseId);
			logger.info("reqPara trainTime:" + trainTime);
			logger.info("reqPara calories:" + calories);
			logger.info("reqPara feelStatus:" + feelStatus);
			logger.info("reqPara actionNum:" + actionNum);
			logger.info("reqPara title:" + title);
			logger.info("reqPara trainDate:" +trainDate);

	        reqPara.setUserid(userid);
	        reqPara.setEnterType(enterType);
	        reqPara.setCourseId(courseId);
	        reqPara.setTrainTime(trainTime);
	        reqPara.setCalories(calories);
	        reqPara.setFeelStatus(feelStatus);
	        reqPara.setActionNum(actionNum);
	        reqPara.setTitle(title);
	        reqPara.setTrainDate(trainDate);
	     
		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		SportRecordsReqPara cdReqPara = (SportRecordsReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

        if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		}else if (StringUtils.isEmpty(cdReqPara.getEnterType())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("进入课程方式为空");
		}else if (StringUtils.isEmpty(cdReqPara.getCourseId())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("课程id为空");
		}else if (StringUtils.isEmpty(cdReqPara.getCalories())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("消耗卡路里为空");
		}else if (StringUtils.isEmpty(cdReqPara.getTrainTime())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("训练时间为空");
		}else if (StringUtils.isEmpty(cdReqPara.getTitle())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("课程标题为空");
		}else {
			flag = true;
		}

		return  flag;
	}

}
